function createBrowserHistory() {
  const globalHistory = window.history;
  let state;
  let listeners = [];

  // 触发监听
  const notify = (newState) => {

    Object.assign(history, newState);

    listeners.forEach(listener => listener(history.location));
  }

  /**
   * 添加路由，移动指针到栈顶
   * 
   * @param {*} pathname 路径名
   * @param {*} nextState 新状态
   */
  const push = (pathname, nextState) => {
    const action = 'PUSH'; // push->PUSH, pop->POP, replace->REPLACE
    if (typeof pathname === 'object') {
      state = pathname.state;
      pathname = pathname.pathname;
    } else {
      state = nextState;
    }
    // pushState 是原生的 history 路由跳转方法
    globalHistory.pushState(state, null, pathname);

    const location = { pathname, state };
    // 触发监听
    notify({ location, action });
  }

  const listen = (listener) => {
    listeners.push(listener);

    // 返回取消监听函数
    return () => listeners = listeners.filter(_listener => _listener !== listener);
  }

  window.addEventListener('popstate', () => {
    const location = {
      pathname: window.location.pathname,
      state: window.location.state
    };

    notify({action: 'POP', location});
  })

  const go = (n) => {
    globalHistory.go(n);
  }

  const goBack = () => {
    globalHistory.go(-1);
  }

  const goForward = () => {
    globalHistory.go(1);
  }

  const history = {
    action: 'POP',
    push,
    listen,
    go,
    goBack,
    goForward,
    location: {
      pathname: window.location.pathname,
      state: window.location.state
    }
  };

  return history;
}


export default createBrowserHistory;